﻿Imports WeatherServices
Imports System.Xml
Imports System.IO
Imports WeatherServices.Service

Public Class Form1
    Public curloc As WxLocation
    Public serv As Service

    Dim lang_at As String

    Public locale As String
    Public usemetric As Boolean
    Public updateint As Integer
    Public dayint As Integer

    Dim timetick As Integer

    Dim x, y As Integer
    Dim newpoint As New Point

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Control.CheckForIllegalCrossThreadCalls = False

        If File.Exists(Application.StartupPath & "\locations.xml") Then
            curloc = LoadCurrentLocation(Application.StartupPath & "\locations.xml")

            If File.Exists(Application.StartupPath & "\settings.xml") Then
                LoadSettings(Application.StartupPath & "\settings.xml")
            Else
                MakeSettings(Application.StartupPath & "\settings.xml")
                Application.Restart()
            End If

            Select Case usemetric
                Case True
                    serv = New Service(curloc, dayint, locale, Service.Units.Metric)

                Case False
                    serv = New Service(curloc, dayint, locale, Service.Units.English)

            End Select

            If locale = "en" Then
            Else
                SetLanguage(locale, Application.StartupPath & "\langcodes.xml")
            End If

            UpdateWeather()
        Else
            Locations.ShowDialog()
        End If
    End Sub

    Private Sub worker_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles worker.DoWork
        serv.Update()
    End Sub

    Dim temp As String
    Dim img As Image
    Dim locat As String

    Private Sub worker_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles worker.RunWorkerCompleted
        lb_temp.Text = serv.Observation.Temperature & "°"

        If serv.Observation.WeatherIcon = Nothing Then
            pic_currentImage.Image = Image.FromFile(String.Format("{0}\44.png", Application.StartupPath & "\weatherpics120"))
        Else
            pic_currentImage.Image = Image.FromFile(String.Format("{0}\{1}.png", Application.StartupPath & "\weatherpics120", serv.Observation.WeatherIcon))
        End If

        lb_loc.Text = curloc.City
        lb_datetime.Text = serv.Observation.ValidDate.ToString

        lb_visibility.Text = serv.Observation.Visibility & " KM"
        lb_humidity.Text = serv.Observation.Humidity & "%"
        lb_wind.Text = String.Format("{0} {1} {2} KM/h", serv.Observation.Wind.WindDirection, lang_at, serv.Observation.Wind.WindSpeed)

        lb_pressure.Text = String.Format("{1} HPa ({0})", serv.Observation.PressureDescription, serv.Observation.Pressure)
        lb_uv.Text = String.Format("{0} ({1})", serv.Observation.UvDescription, serv.Observation.UvIndex)
        lb_heatindex.Text = serv.Observation.HeatIndex

        Dim fday1 As Day = serv.Forecast.Days(0)
        Dim fday2 As Day = serv.Forecast.Days(1)
        Dim fday3 As Day = serv.Forecast.Days(2)
        Dim fday4 As Day = serv.Forecast.Days(3)

        lb_day1.Text = fday1.ValidDate.DayOfWeek.ToString
        lb_day2.Text = fday2.ValidDate.DayOfWeek.ToString
        lb_day3.Text = fday3.ValidDate.DayOfWeek.ToString
        lb_day4.Text = fday4.ValidDate.DayOfWeek.ToString

        If fday1.DayTime IsNot Nothing Then
            pic_1.Image = Image.FromFile(String.Format("{0}\{1}.png", Application.StartupPath & "\weatherpics120", fday1.DayTime.WeatherIcon))
            lb_high1.Text = fday1.MaxTemperature & "°"
            lb_low1.Text = fday1.MinTemperature & "°"
        Else
            pic_1.Image = Image.FromFile(String.Format("{0}\{1}.png", Application.StartupPath & "\weatherpics120", fday1.NightTime.WeatherIcon))
            lb_high1.Text = "N/A"
            lb_low1.Text = fday1.MinTemperature & "°"
        End If

        lb_high2.Text = fday2.MaxTemperature & "°"
        lb_low2.Text = fday2.MinTemperature & "°"
        pic_2.Image = Image.FromFile(String.Format("{0}\{1}.png", Application.StartupPath & "\weatherpics120", fday2.DayTime.WeatherIcon))

        lb_high3.Text = fday3.MaxTemperature & "°"
        lb_low3.Text = fday3.MinTemperature & "°"
        pic_3.Image = Image.FromFile(String.Format("{0}\{1}.png", Application.StartupPath & "\weatherpics120", fday3.DayTime.WeatherIcon))

        lb_high4.Text = fday4.MaxTemperature & "°"
        lb_low4.Text = fday4.MinTemperature & "°"
        pic_4.Image = Image.FromFile(String.Format("{0}\{1}.png", Application.StartupPath & "\weatherpics120", fday4.DayTime.WeatherIcon))
    End Sub

    Private Sub btn_locations_Click(sender As Object, e As EventArgs) Handles btn_locations.Click
        Locations.ShowDialog()

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btn_settings.Click
        settings.ShowDialog()
    End Sub

    Private Sub t_update_Tick(sender As Object, e As EventArgs) Handles t_update.Tick
        If timetick = updateint Then
            UpdateWeather()
            timetick = 0
        Else
            timetick += 1
        End If
    End Sub

    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles btn_close.Click
        Me.Close()
    End Sub

    Private Sub btn_minimize_Click(sender As Object, e As EventArgs) Handles btn_minimize.Click
        Me.WindowState = FormWindowState.Minimized
    End Sub

    Private Sub Label1_MouseDown(sender As Object, e As MouseEventArgs) Handles Label1.MouseDown
        x = Control.MousePosition.X - Me.Location.X
        y = Control.MousePosition.Y - Me.Location.Y
    End Sub

    Private Sub Label1_MouseMove(sender As Object, e As MouseEventArgs) Handles Label1.MouseMove
        If e.Button = Windows.Forms.MouseButtons.Left Then
            'sets the positions 
            newpoint = Control.MousePosition
            newpoint.X -= (x)
            newpoint.Y -= (y)
            'gives it the new location 
            Me.Location = newpoint
        End If
    End Sub

    Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles MyBase.Paint
        Dim rct As Rectangle = Me.ClientRectangle

        Dim g As Graphics = e.Graphics

        g.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
        g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic

        rct.Width -= 1
        rct.Y += 40
        rct.Height -= 41

        g.DrawRectangle(Pens.DimGray, rct)

    End Sub

#Region "Core functions"

    Public Sub UpdateWeather()
        worker.RunWorkerAsync()
    End Sub

    Public Sub ReloadService()
        Select Case usemetric
            Case True
                serv = New Service(curloc, dayint, locale, Service.Units.Metric)

            Case False
                serv = New Service(curloc, dayint, locale, Service.Units.English)

        End Select
    End Sub

    Public Sub MakeSettings(ByVal path As String)
        Dim doc As New XmlDocument

        Dim root As XmlNode = doc.CreateElement("settings")

        Dim loc As XmlElement = doc.CreateElement("locale")
        loc.InnerText = "en"

        Dim dayc As XmlElement = doc.CreateElement("dayint")
        dayc.InnerText = "5"

        Dim usem As XmlElement = doc.CreateElement("metric")
        usem.InnerText = "false"

        Dim updint As XmlElement = doc.CreateElement("update-interval")
        updint.InnerText = "15"

        root.AppendChild(loc)
        root.AppendChild(dayc)
        root.AppendChild(usem)
        root.AppendChild(updint)

        doc.AppendChild(root)

        doc.Save(path)
    End Sub

    Public Sub LoadSettings(ByVal path As String)
        Dim doc As New XmlDocument

        doc.Load(path)

        Dim root As XmlNode = doc.SelectSingleNode("settings")

        Dim loc As XmlNode = root.SelectSingleNode("locale")
        locale = loc.InnerText

        Dim dayc As XmlNode = root.SelectSingleNode("dayint")
        dayint = dayc.InnerText

        Dim usem As XmlNode = root.SelectSingleNode("metric")
        usemetric = usem.InnerText

        Dim upd As XmlNode = root.SelectSingleNode("update-interval")
        updateint = upd.InnerText

    End Sub

    Public Sub SetLanguage(ByVal locale As String, ByVal path As String)
        Dim doc As New XmlDocument

        doc.Load(path)

        Dim root As XmlNode = doc.SelectSingleNode("langcodes")

        Dim subroot As XmlNode = root.SelectSingleNode(locale)

        For Each nod As XmlNode In subroot.SelectNodes("code")
            Select Case nod.Attributes(0).InnerText
                Case "visibility"
                    visib.Text = nod.InnerText

                Case "humidity"
                    humid.Text = nod.InnerText

                Case "wind"
                    wind.Text = nod.InnerText

                Case "at"
                    lang_at = nod.InnerText

                Case "pressure"
                    press.Text = nod.InnerText

                Case "uv"
                    uv.Text = nod.InnerText

                Case "heatindex"
                    heatindex.Text = nod.InnerText

                Case "location"
                    loc.Text = nod.InnerText

                Case "locations"
                    btn_locations.Text = nod.InnerText
                    Locations.Text = nod.InnerText

                Case "add"
                    Locations.btn_add.Text = nod.InnerText
                    searchlocation.btn_add.Text = nod.InnerText

                Case "remove"
                    Locations.btn_remove.Text = nod.InnerText

                Case "select-location"
                    Locations.btn_makecurrent.Text = nod.InnerText

                Case "close"
                    Locations.btn_apply.Text = nod.InnerText

                Case "cancel"
                    searchlocation.btn_cancel.Text = nod.InnerText
                    settings.btn_cancel.Text = nod.InnerText

                Case "select-as-current-location"
                    searchlocation.chk_sel.Text = nod.InnerText

                Case "search"
                    searchlocation.btn_search.Text = nod.InnerText

                Case "save"
                    settings.btn_save.Text = nod.InnerText

                Case "forecast-day-count"
                    settings.fordaycount.Text = nod.InnerText

                Case "units"
                    settings.units.Text = nod.InnerText

                Case "locale"
                    settings.lang.Text = nod.InnerText

                Case "settings"
                    settings.sett.Text = nod.InnerText
                    btn_settings.Text = nod.InnerText
                    settings.Text = nod.InnerText

                Case "update-interval"
                    settings.updateinterval.Text = nod.InnerText

            End Select
        Next
    End Sub

    Public Function LoadCurrentLocation(ByVal path As String) As WxLocation
        Dim city As String = Nothing
        Dim country As String = Nothing
        Dim lat As String = Nothing
        Dim lng As String = Nothing
        Dim woeid As String = Nothing
        Dim state As String = Nothing
        Dim statename As String = Nothing
        Dim sel As String = Nothing

        Dim doc As New XmlDocument
        doc.Load(path)

        For Each lc As XmlNode In doc.SelectNodes("/locations/location")
            If lc.SelectSingleNode("selected").InnerText = "true" Then
                city = lc.SelectSingleNode("city").InnerText
                country = lc.SelectSingleNode("country").InnerText
                lat = lc.SelectSingleNode("latitude").InnerText
                lng = lc.SelectSingleNode("longitude").InnerText
                woeid = lc.SelectSingleNode("parentId").InnerText
                state = lc.SelectSingleNode("state").InnerText
                statename = lc.SelectSingleNode("statename").InnerText
                sel = lc.SelectSingleNode("selected").InnerText
            End If
        Next

        Return New WxLocation(city, state, statename, country, woeid, lat, lng, sel)
    End Function

#End Region

End Class


